package com.zhongshengnetwork.rightbe.lang.activity;

import android.content.Context;
import android.content.Intent;
//import android.support.annotation.NonNull;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CircleLangModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.view.CircleLangFragment;
import com.zhongshengnetwork.rightbe.login.LoginActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CircleActivity extends AppBaseActivity {

    private EditText search_edit;
    private int pageindex = 0;
    private static final int Records = 20;
    private List<CircleLangModel> list;
    private ListView listview;
    private MyAdapter adapter;
    private RefreshLayout mRefreshLayout;
    private String nickname = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circle);
        search_edit = (EditText) findViewById(R.id.search_edit);
        pageindex = 0;
        if (list == null){
            list = new ArrayList<CircleLangModel>();
        }
        listview=(ListView) findViewById(R.id.circle_lang_listview);
        adapter=new MyAdapter();
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (list == null || list.size() == 0){
                    return;
                }
                Log.e("TAG","position="+position);
                int index = position;// - 1;
                while (index < 0){//解决部分手机点击第一条不是从1开始的问题
                    index+=1;
                }
                CircleLangModel model = list.get(index);
                Intent intent = new Intent(CircleActivity.this, UserLangActivity.class);
                intent.putExtra(APIKey.useridKey,model.getUserid());
                intent.putExtra(APIKey.typeKey,1);
                intent.putExtra(APIKey.titleKey,model.getNickname());
                startActivity(intent);
            }
        });
        listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                if (i == SCROLL_STATE_FLING ||
                        i == SCROLL_STATE_TOUCH_SCROLL){
                    hintKeyBoard();
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        mRefreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        //设置 Header 为 贝塞尔雷达 样式
        mRefreshLayout.setRefreshHeader(new BezierRadarHeader(CircleActivity.this).setEnableHorizontalDrag(true));//BezierRadarHeader
        //设置 Footer 为 球脉冲 样式
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(CircleActivity.this).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
        mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
        mRefreshLayout.setEnableRefresh(true);//启用刷新
        mRefreshLayout.setEnableLoadMore(true);//启用加载
        //刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //refreshlayout.finishRefresh();
                pageindex = 0;
                getData();
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //refreshLayout.finishLoadMore();
                getData();
            }
        });
        mRefreshLayout.autoRefresh(100,300,1f,false);

        search_edit.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        search_edit.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        RelativeLayout lang_search_layout = (RelativeLayout) findViewById(R.id.lang_search_layout);
        lang_search_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        RelativeLayout search_top = (RelativeLayout) findViewById(R.id.search_top);
        search_top.setBackgroundColor(AppThemeUtils.getInstance().getSearchBgColor());
        RelativeLayout search_shape_layout = (RelativeLayout) findViewById(R.id.search_shape_layout);
        search_shape_layout.setBackgroundResource(AppThemeUtils.getInstance().getSearchBackground());
        listview.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    private void getData(){
        if (listview == null){
            return;
        }

        hintKeyBoard();

        if (search_edit != null){
            if (search_edit.getText() != null){
                String text = search_edit.getText().toString();
                nickname = text;
            }else {
                nickname = "";
            }
        }

        new Thread(){
            @Override
            public void run() {
                super.run();
                //首次从缓存里面获取数据
                if (list.size() == 0 && pageindex == 0){
                    String data = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.CircleData,"");
                    if (!CommonUtils.isEmpty(data)){
                        final List<CircleLangModel> l = GsonTools.getCircleLangModel(data);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (l != null && l.size() > 0){
                                    list.addAll(l);
                                }
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }
                }
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                map.put("pageindex",pageindex+"");
                map.put("pagerecords",Records+"");
                map.put("nickname",CommonUtils.formatString(nickname));
                HttpsUtils.miniAppDo(map, "miniapp/langappid/langrange.do", new HttpCallBack() {
                    @Override
                    public void onSuccess(final String data) {
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<CircleLangModel> l = GsonTools.getCircleLangModel(data);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        list.clear();
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    if (l != null && l.size() > 0){
                                        if (pageindex == 0){
                                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.CircleData,data);
                                        }
                                        if (l.size() >= Records){
                                            //listview.setPullLoadEnable(true);
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            //listview.setPullLoadEnable(false);
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        list.addAll(l);
                                    }else {
                                        //listview.setPullLoadEnable(false);
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    adapter.notifyDataSetChanged();
                                    if (pageindex == 0 && l != null && l.size() > 0){
                                        listview.setSelection(0);
                                    }
                                    if (l != null && l.size() > 0){
                                        pageindex += 1;
                                    }
                                }
                            });

                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    CustomApplication.showTip(commonModel, CircleActivity.this);
                                }
                            });

                        }
                    }

                    @Override
                    public void onError(String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mRefreshLayout.getState() == RefreshState.Loading){
                                    //listview.stopLoadMore();
                                    mRefreshLayout.finishLoadMore();
                                }else {
                                    //listview.stopRefresh(true);
                                    mRefreshLayout.finishRefresh();
                                }
                            }
                        });
                    }
                });
            }
        }.start();

    }

    public void onClickBack(View view){
        hintKeyBoard();
        finish();
    }

    public void onClickSearch(View view){
        hintKeyBoard();
        String text = search_edit.getText().toString();
        nickname = text;
        if (mRefreshLayout != null){
            Log.e("TAG","进来获取数据了刷新界面");
                /*
                @param delayed 开始延时
                @param duration 拖拽动画持续时间
                @param dragRate 拉拽的高度比率（要求 ≥ 1 ）
                */
            mRefreshLayout.autoRefresh(100,300,1f,false);
        }
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(CircleActivity.this, R.layout.lang_circle_item,null);
            }
            View view=convertView;
            //view = LayoutInflater.from(getActivity()).inflate(R.layout.lang_circle_item, null);
            ImageView lang_circle_header = (ImageView) view.findViewById(R.id.lang_circle_header);
            ImageView privateIcon = (ImageView) view.findViewById(R.id.private_icon);
            TextView lang_circle_nickname = (TextView) view.findViewById(R.id.lang_circle_nickname);
            Button lang_circle_care = (Button) view.findViewById(R.id.lang_circle_care);
            TextView lang_circle_smart_value = (TextView) view.findViewById(R.id.lang_circle_smart_value);
            TextView lang_circle_count = (TextView) view.findViewById(R.id.lang_circle_count);
            TextView lang_comment_count = (TextView) view.findViewById(R.id.lang_comment_count);
            TextView lang_circle_care_count = (TextView) view.findViewById(R.id.lang_circle_care_count);
            CircleLangModel model = list.get(position);

            Glide.with(CircleActivity.this).load(model.getHeader()).transform(new CircleTransform(CircleActivity.this)).dontAnimate().into(lang_circle_header);
            if (!CommonUtils.isEmpty(model.getPrivateIcon())){
                privateIcon.setVisibility(View.VISIBLE);
                Glide.with(CircleActivity.this).load(model.getPrivateIcon()).transform(new CircleTransform(CircleActivity.this)).dontAnimate().into(privateIcon);
            }else {
                privateIcon.setVisibility(View.GONE);
            }
            lang_circle_nickname.setText(model.getNickname());
            lang_circle_care.setTag(position);
            if (model.iscare() == true){
                lang_circle_care.setVisibility(View.INVISIBLE);
            }else {
                lang_circle_care.setVisibility(View.VISIBLE);
                lang_circle_care.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onClickCare((int)v.getTag());
                    }
                });
            }
            lang_circle_smart_value.setText(CommonUtils.getDisplayCount(model.getLevel())+"");
            lang_circle_count.setText((model.getLangcount()-model.getLifecount())+"");
            lang_comment_count.setText(model.getWeishucount()+"");
            lang_circle_care_count.setText(model.getFanscount()+"");

            RelativeLayout lang_circle_item_layout = (RelativeLayout) view.findViewById(R.id.lang_circle_item_layout);
            lang_circle_item_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            LinearLayout lang_circle_line = (LinearLayout) view.findViewById(R.id.lang_circle_line);
            lang_circle_line.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            lang_circle_nickname.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

            ImageView lang_member_icon = (ImageView) view.findViewById(R.id.lang_member_icon);
            if (!CommonUtils.isEmpty(model.getMemberIcon())){
                lang_member_icon.setVisibility(View.VISIBLE);
                try{
                    Glide.with(CircleActivity.this).load(model.getMemberIcon()).
                            diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(lang_member_icon);
                }catch (Exception e){
                    LangPublishActivity.uploadError("智慧排行点赞列表加载图片报错："+e.getLocalizedMessage());
                }

            }else {
                lang_member_icon.setVisibility(View.INVISIBLE);
            }

            return view;
        }

    }

    //点击关注
    private void onClickCare(final int position){
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(CircleActivity.this,LoginActivity.class);
            startActivity(intent);
            return;
        }
        final CircleLangModel model = list.get(position);
        if (model.iscare() == true){
            return;
        }
        model.setIscare(true);
        list.set(position,model);
        adapter.notifyDataSetChanged();

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("authorid", model.getUserid());
        String url = "miniapp/"+"langappid"+"/addcare.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
            }

            @Override
            public void onError(String msg) {
            }
        });
    }

}
